package org.wiztools.te.plugin.helper;

public class CommentHelper{
	public static String singleLineComment(String str, String commentChar){
		String[] lines = str.split("\n");
		StringBuffer sb = new StringBuffer();
		for(String line: lines){
			if(!line.matches("\\s*")){
				sb.append(commentChar).append(" ").append(line).append("\n");
			}
			else{
				sb.append(line).append("\n");
			}
		}
		
		// Remove the last appended `\n'
		sb.deleteCharAt(sb.length()-1);
		
		return sb.toString();
	}

	private static String[] reChars = new String[]{"*", "<", ">", "|", "^", "$"};
	private static String escapeRE(String str){
		for(String reChar: reChars){
			str = str.replaceAll("\\"+reChar, "\\\\"+reChar);
		}
		return str;
	}
	
	public static String singleLineUnComment(String str, String commentChar){
		String[] lines = str.split("\n");
		StringBuffer sb = new StringBuffer();
		for(String line: lines){
			if(line.matches("\\s*"+commentChar+"\\s{0,1}.*")){
				sb.append(line.replaceFirst(commentChar+"\\s{0,1}", "")).append("\n");
			}
			else{
				sb.append(line).append("\n");
			}
		}
		// Remove the last appended `\n'
		sb.deleteCharAt(sb.length()-1);
		
		return sb.toString();
	}
	
	/*
	replaceEndComment - If the endComment string is found in the text,
	it is replaced with this string.
	*/
	public static String multiLineComment(String str, 
						String startComment, 
						String endComment, 
						String replaceEndComment){
		StringBuffer sb = new StringBuffer(startComment).append(" ");
		String escEndComment = escapeRE(endComment);
		sb.append(str.replaceAll(escEndComment, replaceEndComment));
		sb.append(" ").append(endComment);
		
		return sb.toString();
	}
}
